package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.AttachTypeEnum;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.PyqJobDetailStatusEnum;
import com.uzai.common.enums.PyqJobStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.pyq.pyqjob.PyqJobDto;
import com.uzai.console.dto.pyq.pyqjob.PyqJobIdDto;
import com.uzai.console.dto.pyq.pyqjob.PyqJobIdListDto;
import com.uzai.console.dto.pyq.pyqjob.PyqJobQuery;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailDeleteDto;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailQuery;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.pyq.*;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.pyq.pyqjob.PyqJobVo;
import com.uzai.console.vo.pyq.pyqjobdetail.PyqJobDetailVo;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 朋友圈发送任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqJobServiceImpl implements PyqJobService {

    Logger logger = LoggerFactory.getLogger(PyqJobServiceImpl.class);

    @Autowired
    private PyqJobMapper pyqJobMapper;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private  PyqCommentTemplateMapper pyqCommentTemplateMapper;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private PyqMaterialService pyqMaterialService;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private PyqJobSyncService pyqJobSyncService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private PyqMaterialMapper pyqMaterialMapper;
    @Autowired
    private PyqLlyGoodsMapper pyqLlyGoodsMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private DeviceService deviceService;

    /**
     * 查询朋友圈发送任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobQuery
     * @return null
     */
    public Page<PyqJobVo> findPyqJobList(PyqJobQuery pyqJobQuery){
        //新建返回到页面的LIST对象
        List<PyqJobVo> pyqJobPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<PyqJob> page = new Page<>();
        pyqJobQuery.convert(page);
        ArrayList<PyqJob> pyqJobList =  pyqJobMapper.findByList(page, pyqJobQuery);
        if(pyqJobList != null && pyqJobList.size() > 0){
            for (PyqJob pyqJob : pyqJobList) {
                PyqJobVo pyqJobPageVo = new PyqJobVo();
                BeanUtils.copyProperties(pyqJob, pyqJobPageVo);

                //朋友圈附件类型
                if(pyqJob.getAttachType() != null){
                    AttachTypeEnum attachTypeEnum = AttachTypeEnum.getById(pyqJob.getAttachType());
                    if(attachTypeEnum != null){
                        pyqJobPageVo.setAttachTypeName(attachTypeEnum.getDesc());
                    }
                }

                //封装图片
                if(StringUtils.isNotBlank(pyqJobPageVo.getFeedMedia())){
                    List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqJobPageVo.getFeedMedia(), FeedMedia.class);
                    if(feedMediaList != null && feedMediaList.size() > 0){
                        List<String> imgList = new ArrayList<>();
                        if(Tools.getInteger(pyqJob.getAttachType()).intValue() == 2){
                            for (FeedMedia feedMedia : feedMediaList) {
                                if(StringUtils.isNotBlank(feedMedia.getUrl())){
                                    imgList.add(feedMedia.getUrl());
                                }
                            }
                        }else{
                            for (FeedMedia feedMedia : feedMediaList) {
                                if(StringUtils.isNotBlank(feedMedia.getCover())){
                                    imgList.add(feedMedia.getCover());
                                }else{
                                    if(StringUtils.isNotBlank(feedMedia.getThumb())){
                                        imgList.add(feedMedia.getThumb());
                                    }
                                }
                            }
                        }
                        pyqJobPageVo.setImgList(imgList);
                        pyqJobPageVo.setImgs(JSONObject.toJSONString(imgList));
                    }
                }else{ //旧版接口
                    if(StringUtils.isNotBlank(pyqJobPageVo.getImgs())){
                        List<String> imgList = JSONObject.parseArray(pyqJobPageVo.getImgs(), String.class);
                        pyqJobPageVo.setImgList(imgList);
                        pyqJobPageVo.setImgs(JSONObject.toJSONString(imgList));
                    }
                }

                //视频号朋友圈，如果图片为空，封装首图
                if(StringUtils.isBlank(pyqJobPageVo.getImgs())){
                    if(AttachTypeEnum.SHIPINHAO.getValue().intValue() == Tools.getInteger(pyqJobPageVo.getAttachType()).intValue()){
                        List<String> imgList = new ArrayList<>();
                        imgList.add(Const.PyqFirstImg.SHIPINHAO);
                        pyqJobPageVo.setImgList(imgList);
                        pyqJobPageVo.setImgs(JSONObject.toJSONString(imgList));
                    }
                }

                pyqJobPageVoList.add(pyqJobPageVo);

                try{
                    //已发送
                    Long sendedCount = 0L;
                    //查询已发送数
                    PyqJobDetailQuery pyqJobDetailQuery = new PyqJobDetailQuery();
                    pyqJobDetailQuery.setJobId(pyqJobPageVo.getId());
                    pyqJobDetailQuery.setMerId(pyqJobQuery.getMerId());
                    pyqJobDetailQuery.setStatus(PyqJobDetailStatusEnum.SENDED.getValue());//发送完成的朋友圈
                    Page<PyqJobDetailVo> pyqJobDetailPage = pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery);
                    if(pyqJobDetailPage != null){
                        sendedCount = Tools.getLong(pyqJobDetailPage.getTotal());
                        //已发送数等于发送总数，修改状态已完成
                        if(sendedCount.longValue() == Tools.getInteger(pyqJobPageVo.getTotalCount()).intValue()){
                            PyqJob pyqJobUpdate = new PyqJob();
                            pyqJobUpdate.setMerId(pyqJobQuery.getMerId());
                            pyqJobUpdate.setId(pyqJobPageVo.getId());
                            pyqJobUpdate.setStatus(PyqJobStatusEnum.COMPLETE.getValue());
                            pyqJobUpdate.setUpdateTime(DateUtil.getNowTime());
                            pyqJobMapper.updateStatusById(pyqJobUpdate);
                        }
                    }
                    //封装已发送数
                    pyqJobPageVo.setSendedCount(sendedCount.intValue());

                    //发送失败
                    //查询已发送数
                    Long failSendCount = 0L;
                    PyqJobDetailQuery pyqJobDetailQuery_failSend = new PyqJobDetailQuery();
                    pyqJobDetailQuery_failSend.setJobId(pyqJobPageVo.getId());
                    pyqJobDetailQuery_failSend.setMerId(pyqJobQuery.getMerId());
                    pyqJobDetailQuery_failSend.setStatus(PyqJobDetailStatusEnum.SENDFAIL.getValue());//发送失败的朋友圈
                    Page<PyqJobDetailVo> pyqJobDetailPage_failSend = pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery_failSend);
                    if(pyqJobDetailPage_failSend != null){
                        failSendCount = Tools.getLong(pyqJobDetailPage_failSend.getTotal());
                    }
                    //封装已发送数
                    pyqJobPageVo.setFailSendCount(failSendCount.intValue());

                    //查询未发送数
                    Long noSendCount = 0L;
                    PyqJobDetailQuery pyqJobDetailQuery_noSend = new PyqJobDetailQuery();
                    pyqJobDetailQuery_noSend.setJobId(pyqJobPageVo.getId());
                    pyqJobDetailQuery_noSend.setMerId(pyqJobQuery.getMerId());
                    pyqJobDetailQuery_noSend.setStatus(PyqJobDetailStatusEnum.NOSEND.getValue());//未发送的朋友圈
                    Page<PyqJobDetailVo> pyqJobDetailPage_noSend = pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery_noSend);
                    if(pyqJobDetailPage_noSend != null){
                        noSendCount = Tools.getLong(pyqJobDetailPage_noSend.getTotal());
                    }
                    //封装已发送数
                    pyqJobPageVo.setNoSendCount(noSendCount.intValue());

                    //查询发送中的数
                    Long sendingCount = 0L;
                    PyqJobDetailQuery pyqJobDetailQuery_sending = new PyqJobDetailQuery();
                    pyqJobDetailQuery_sending.setJobId(pyqJobPageVo.getId());
                    pyqJobDetailQuery_sending.setMerId(pyqJobQuery.getMerId());
                    pyqJobDetailQuery_sending.setStatus(PyqJobDetailStatusEnum.SENDING.getValue());//发送中的朋友圈
                    Page<PyqJobDetailVo> pyqJobDetailPage_sending = pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery_sending);
                    if(pyqJobDetailPage_sending != null){
                        sendingCount = Tools.getLong(pyqJobDetailPage_sending.getTotal());
                    }
                    //封装发送中的数
                    pyqJobPageVo.setSendingCount(sendingCount.intValue());
                }catch (Exception e){

                }
            }
        }

        //返回到页面分页对象
        Page<PyqJobVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(pyqJobPageVoList);

        return pageVo;
    }

    /**
     * 查询朋友圈发送任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobIdDto
     * @return null
     */
    public PyqJobVo findPyqJob(PyqJobIdDto pyqJobIdDto){
        if(pyqJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqJob pyqJob = pyqJobMapper.selectById(pyqJobIdDto.getId(), pyqJobIdDto.getMerId());

        if(pyqJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该朋友圈发送任务不存在");
        }

        PyqJobVo pyqJobVo = new PyqJobVo();
        BeanUtils.copyProperties(pyqJob, pyqJobVo);

        //封装图片
        if(StringUtils.isNotBlank(pyqJobVo.getFeedMedia())){
            List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqJobVo.getFeedMedia(), FeedMedia.class);
            if(feedMediaList != null && feedMediaList.size() > 0){
                List<String> imgList = new ArrayList<>();
                if(Tools.getInteger(pyqJob.getAttachType()).intValue() == 2){
                    for (FeedMedia feedMedia : feedMediaList) {
                        imgList.add(feedMedia.getUrl());
                    }
                }else{
                    for (FeedMedia feedMedia : feedMediaList) {
                        imgList.add(feedMedia.getCover());
                    }
                }
                pyqJobVo.setImgList(imgList);
                pyqJobVo.setImgs(JSONObject.toJSONString(imgList));
            }
        }else{ //旧版接口
            if(StringUtils.isNotBlank(pyqJobVo.getImgs())){
                List<String> imgList = JSONObject.parseArray(pyqJobVo.getImgs(), String.class);
                pyqJobVo.setImgList(imgList);
                pyqJobVo.setImgs(JSONObject.toJSONString(imgList));
            }
        }

        return pyqJobVo;
    }

    /**
     * 添加朋友圈发送任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDto
     * @return null
     */
    @Transactional
    public void addPyqJob(PyqJobDto pyqJobDto){

        if(pyqJobDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqJobDto.getDevicePlanId(), pyqJobDto.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqJobDto.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        if(pyqJobDto.getType() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择类型");
        }

        //商品，额外增加判断
        if(pyqJobDto.getType().intValue() == 1){//图文
            pyqJobDto.setPlatform(20); //图文默认平台=20
        }else{
            if(pyqJobDto.getPlatform() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择平台");
            }

            if(StringUtils.isBlank(pyqJobDto.getItemId())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入商品链接/id");
            }
        }

        //封装朋友圈任务
        Integer now = DateUtil.getNowTime();
        PyqJob pyqJob = new PyqJob();
        pyqJob.setId(IdWorker.getId());
        pyqJob.setMerId(pyqJobDto.getMerId());
        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
        pyqJob.setStatus(PyqJobStatusEnum.NOSTART.getValue());
        pyqJob.setType(pyqJobDto.getType());
        pyqJob.setSource(0); //手动发送
        pyqJob.setPlatform(pyqJobDto.getPlatform());
        pyqJob.setDevicePlanId(pyqJobDto.getDevicePlanId());
        pyqJob.setItemId(pyqJobDto.getItemId());
        pyqJob.setCouponId(pyqJobDto.getCouponId());
        pyqJob.setContentId(pyqJobDto.getContentId());
        //朋友圈内容替换变量
        String content = Tools.getStr(pyqJobDto.getContent());
        //券后价
        Double finalPrice = Tools.getDouble(pyqJobDto.getFinalPrice());
        //优惠券金额
        Double couponVal = Tools.getDouble(pyqJobDto.getCouponVal());

        //新版朋友圈接口新增加字段
        //封装附件类型
        Integer attachType = pyqJobDto.getAttachType();
        if(attachType == null){
            attachType = 2;
        }

        if(attachType.intValue() == 2){
            //封装附件对象
            List<FeedMedia> feedMediaList = new ArrayList<>();
            //图片
            List<String> imgList = pyqJobDto.getImgList();
            if(imgList == null){
                imgList = new ArrayList<>();
            }
            if(imgList.size() > 9){
                imgList = imgList.subList(0, 9);
            }
            for (String item : imgList){
                if(StringUtils.isNotBlank(item)){
                    FeedMedia feedMedia = new FeedMedia();
                    feedMedia.setMediaType(2);
                    feedMedia.setUrl(item);
                    feedMediaList.add(feedMedia);
                }
            }
            pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        }else{
            pyqJob.setFeedMedia(pyqJobDto.getFeedMedia());
        }

        pyqJob.setAttachType(attachType);//图文
        pyqJob.setVideoNumber(pyqJobDto.getVideoNumber());
        pyqJob.setImgs(null);  //新版朋友圈接口，img不存放任何东西

        pyqJob.setCommentId(pyqJobDto.getCommentId());
        //评论内容替换变量
        String commentContent = Tools.getStr(pyqJobDto.getCommentContent());

        if(pyqJobDto.getType().intValue() == 0){ //商品
            //先转链
            TurnlinkDto turnlinkDto = new TurnlinkDto();
            turnlinkDto.setMerId(pyqJobDto.getMerId());
            turnlinkDto.setPlatform(pyqJobDto.getPlatform());
            turnlinkDto.setCouponId(pyqJobDto.getCouponId());
            turnlinkDto.setDeviceUniqueId(deviceUniqueIdList.get(0));
            turnlinkDto.setDevicePlanId(pyqJobDto.getDevicePlanId());
            turnlinkDto.setItemId(pyqJobDto.getItemId());
            SimpleTurnlinkVo simpleTurnlinkVo = pyqMaterialService.getGoodInfo(turnlinkDto);
            pyqJob.setCouponVal(simpleTurnlinkVo.getCouponVal());
            pyqJob.setFinalPrice(simpleTurnlinkVo.getFinalPrice());
            //原价 = 券后价 + 优惠券金额
            double price = Math.add(finalPrice.doubleValue(), couponVal.doubleValue());
            content = content.replace("[商品标题]",Tools.getStr(simpleTurnlinkVo.getItemName()))
                    .replace("[原价]",  String.valueOf(price))
                    .replace("[券后价]", String.valueOf(finalPrice.doubleValue()));
            commentContent = commentContent.replace("[商品标题]",Tools.getStr(simpleTurnlinkVo.getItemName()))
                    .replace("[原价]",  String.valueOf(price))
                    .replace("[券后价]", String.valueOf(finalPrice.doubleValue()));

        }else if(pyqJobDto.getType().intValue() == 1){//图文

        }

        //赋值内容
        pyqJob.setContent(content);

        //去空评论
        List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
        if(commentContentList != null && commentContentList.size() > 0){
            commentContentList.removeIf(s ->  StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        pyqJob.setCommentContent(commentContent);
        pyqJob.setTotalCount(deviceUniqueIdList.size());
        pyqJob.setCreateTime(now);
        pyqJob.setUpdateTime(now);
        if(pyqJobDto.getSendTime() == null ){
            pyqJob.setSendTime(now + 5*60); //为空表示立即发送，现在时间+5分钟
        }else{
            pyqJob.setSendTime(pyqJobDto.getSendTime());
        }

        //保存类型(0-仅发送；1-发送并保存素材；2-仅保存素材)
        if(Tools.getInteger(pyqJobDto.getSaveMaterialFlag()).intValue() == 0){//仅发送
            //后台添加发送明细
            pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqDevicePlan.getDomain());
        }else if(Tools.getInteger(pyqJobDto.getSaveMaterialFlag()).intValue() == 1){ //发送并保存素材
            //后台添加发送明细
            pyqJobSyncService.addJobSync(pyqJob, deviceUniqueIdList, pyqDevicePlan.getDomain());

            //保存素材
            PyqMaterial pyqMaterial = new PyqMaterial();
            pyqMaterial.setId(IdWorker.getId());
            pyqMaterial.setMerId(pyqJob.getMerId());
            pyqMaterial.setDeviceType(pyqDevicePlan.getDeviceType());
            pyqMaterial.setType(pyqJob.getType());
            pyqMaterial.setPlatform(pyqJob.getPlatform());
            pyqMaterial.setDevicePlanId(pyqJob.getDevicePlanId());
            pyqMaterial.setItemId(pyqJob.getItemId());
            pyqMaterial.setCouponId(pyqJob.getCouponId());
            pyqMaterial.setCouponVal(pyqJob.getCouponVal());
            pyqMaterial.setFinalPrice(pyqJob.getFinalPrice());
            pyqMaterial.setContentId(pyqJob.getContentId());
            pyqMaterial.setContent(pyqJob.getContent());
            pyqMaterial.setImgs(pyqJob.getImgs());
            pyqMaterial.setCommentId(pyqJob.getCommentId());
            pyqMaterial.setCommentContent(pyqJob.getCommentContent());
            //新版朋友圈接口新增加字段
            pyqMaterial.setAttachType(pyqJob.getAttachType());
            pyqMaterial.setVideoNumber(pyqJob.getVideoNumber());
            pyqMaterial.setFeedMedia(pyqJob.getFeedMedia());
            pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西
            pyqMaterial.setCreateTime(now);
            pyqMaterial.setUpdateTime(now);
            pyqMaterialMapper.insert(pyqMaterial);
        }else{
            //保存素材
            PyqMaterial pyqMaterial = new PyqMaterial();
            pyqMaterial.setId(IdWorker.getId());
            pyqMaterial.setMerId(pyqJob.getMerId());
            pyqMaterial.setDeviceType(pyqDevicePlan.getDeviceType());
            pyqMaterial.setType(pyqJob.getType());
            pyqMaterial.setPlatform(pyqJob.getPlatform());
            pyqMaterial.setDevicePlanId(pyqJob.getDevicePlanId());
            pyqMaterial.setItemId(pyqJob.getItemId());
            pyqMaterial.setCouponId(pyqJob.getCouponId());
            pyqMaterial.setCouponVal(pyqJob.getCouponVal());
            pyqMaterial.setFinalPrice(pyqJob.getFinalPrice());
            pyqMaterial.setContentId(pyqJob.getContentId());
            pyqMaterial.setContent(pyqJob.getContent());
            pyqMaterial.setImgs(pyqJob.getImgs());
            pyqMaterial.setCommentId(pyqJob.getCommentId());
            pyqMaterial.setCommentContent(pyqJob.getCommentContent());
            //新版朋友圈接口新增加字段
            pyqMaterial.setAttachType(pyqJob.getAttachType());
            pyqMaterial.setVideoNumber(pyqJob.getVideoNumber());
            pyqMaterial.setFeedMedia(pyqJob.getFeedMedia());
            pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西
            pyqMaterial.setCreateTime(now);
            pyqMaterial.setUpdateTime(now);
            pyqMaterialMapper.insert(pyqMaterial);
        }
    }

    /**
     * 修改朋友圈发送任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobDto
     * @return null
     */
    public void updatePyqJob(PyqJobDto pyqJobDto){
        if(pyqJobDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(pyqJobDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqJobDto.getDevicePlanId(), pyqJobDto.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqJobDto.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        if(pyqJobDto.getType() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择类型");
        }

        //商品，额外增加判断
        if(pyqJobDto.getType().intValue() == 1){//图文
            pyqJobDto.setPlatform(20); //图文默认平台=20
        }else{
            if(pyqJobDto.getPlatform() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择平台");
            }

            if(StringUtils.isBlank(pyqJobDto.getItemId())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入商品链接/id");
            }
        }

        PyqJob pyqJob = pyqJobMapper.selectById(pyqJobDto.getId(), pyqJobDto.getMerId());
        if(pyqJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发送任务不存在");
        }

        if(pyqJob.getStatus().intValue() != PyqJobStatusEnum.NOSTART.getValue().intValue()){ //不是未开始状态，不能修改
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发送任务已经开始发送，不能修改");
        }

        pyqJob.setType(pyqJobDto.getType());
        pyqJob.setPlatform(pyqJobDto.getPlatform());
        pyqJob.setDevicePlanId(pyqJobDto.getDevicePlanId());
        pyqJob.setDeviceType(pyqDevicePlan.getDeviceType());
        pyqJob.setItemId(pyqJobDto.getItemId());
        pyqJob.setCouponId(pyqJobDto.getCouponId());
        pyqJob.setCouponVal(pyqJobDto.getCouponVal());
        pyqJob.setFinalPrice(pyqJobDto.getFinalPrice());
        pyqJob.setContentId(pyqJobDto.getContentId());
        pyqJob.setContent(pyqJobDto.getContent());

        Integer attachType = pyqJobDto.getAttachType();
        if(attachType == null){
            attachType = 2;
        }

        //封装视频号信息
        String videoNumber = pyqJob.getVideoNumber();
        if(pyqJob.getAttachType().intValue() == 2){
            //封装附件对象
            List<FeedMedia> feedMediaList = new ArrayList<>();
            //图片
            List<String> imgList = pyqJobDto.getImgList();
            if(imgList == null){
                imgList = new ArrayList<>();
            }
            if(imgList.size() > 9){
                imgList = imgList.subList(0, 9);
            }
            for (String item : imgList){
                if(StringUtils.isNotBlank(item)){
                    FeedMedia feedMedia = new FeedMedia();
                    feedMedia.setMediaType(2);
                    feedMedia.setUrl(item);
                    feedMediaList.add(feedMedia);
                }
            }
            pyqJob.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        }

        //新版朋友圈接口，img不存放任何东西
        pyqJob.setImgs(null);

        pyqJob.setCommentId(pyqJobDto.getCommentId());
        String commentContent = Tools.getStr(pyqJobDto.getCommentContent());
        //去空评论
        List<String> commentContentList = JSONObject.parseArray(commentContent, String.class);
        if(commentContentList != null && commentContentList.size() > 0){
            commentContentList.removeIf(s ->  StringUtils.isBlank(s));
            commentContent = JSONObject.toJSONString(commentContentList);
        }
        pyqJob.setCommentContent(commentContent);

        pyqJob.setTotalCount(deviceUniqueIdList.size());
        Integer now = DateUtil.getNowTime();
        pyqJob.setUpdateTime(now);

        if(pyqJobDto.getSendTime() == null ){
            pyqJob.setSendTime(now + 5*60); //为空表示立即发送，现在时间+5分钟
        }else{
            pyqJob.setSendTime(pyqJobDto.getSendTime());
        }

        try{
            //清空所有的发送明细
            DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
            deleteByQueryRequest.setQuery(new TermQueryBuilder("jobId", pyqJob.getId()));
            //批量删除
            //先查询该朋友圈明细
            String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobDto.getMerId());
            elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_pyq_job_detail, deleteByQueryRequest);
            Thread.sleep(100);
            //后台修改发送明细
            pyqJobSyncService.updateJobSync(pyqJob, deviceUniqueIdList, pyqDevicePlan.getDomain());
            Thread.sleep(2000);
        }catch (Exception e){
            logger.error("修改朋友任务失败，info={}"+ e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败");
        }
    }

    /**
     * 删除朋友圈任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobIdListDto
     * @return null
     */
    @Transactional
    public void deletePyqJob(PyqJobIdListDto pyqJobIdListDto){

//        if(true){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前版本不支持删除朋友圈任务功能");
//        }

        if(pyqJobIdListDto.getIdList() == null || pyqJobIdListDto.getIdList().size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择需要删除的记录");
        }

        //先查询该朋友圈明细
        String uzai_pyq_job_detail = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_PYQ_JOB_DETAIL, pyqJobIdListDto.getMerId());

        for(Long id : pyqJobIdListDto.getIdList()){

            PyqJob pyqJob = pyqJobMapper.selectById(id, pyqJobIdListDto.getMerId());

            if(pyqJob == null ){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的朋友圈发送记录不存在");
            }

            if(pyqJob.getStatus().intValue() != PyqJobStatusEnum.NOSTART.getValue().intValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的发送记录有未开始状态的记录");
            }

            //删除朋友圈任务
            pyqJobMapper.deleteById(id, pyqJobIdListDto.getMerId());
            //删除朋友圈明细
            //清空所有的发送明细
            DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
            deleteByQueryRequest.setQuery(new TermQueryBuilder("jobId", id));
            try{
                //批量删除
                elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_pyq_job_detail, deleteByQueryRequest);
            }catch (Exception e){
                logger.error("删除朋友圈明细请求出现异常,index="+ EsIndexName.UZAI_WECHAT_REQ_USER);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "删除失败");
            }
        }

        //延迟0.2秒
        try{
            Thread.sleep(200);
        }catch (Exception e){

        }

    }

    /**
     * 删除微信朋友圈
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobIdDto
     * @return null
     */
    public void deleteWxPyq(PyqJobIdDto pyqJobIdDto){
        if(pyqJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        PyqJobDetailQuery pyqJobDetailQuery = new PyqJobDetailQuery();
        pyqJobDetailQuery.setJobId(pyqJobIdDto.getId());
        Page<PyqJobDetailVo> pyqJobDetailVoPage =  pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery);
        if(pyqJobDetailVoPage != null){
            int total = (int)pyqJobDetailVoPage.getTotal();
            int times =  total / pyqJobDetailQuery.getSize() + 1;
            for(int i = 1; i <= times ; i++){
                pyqJobDetailQuery.setCurrent(i);
                pyqJobDetailVoPage =  pyqJobDetailService.findPyqJobDetailList(pyqJobDetailQuery);
                if(pyqJobDetailVoPage != null){
                    List<PyqJobDetailVo> pyqJobDetailVoList = pyqJobDetailVoPage.getRecords();
                    if(pyqJobDetailVoList != null){
                        for(PyqJobDetailVo pyqJobDetailVo : pyqJobDetailVoList){
                            PyqJobDetailDeleteDto pyqJobDetailDeleteDto = new PyqJobDetailDeleteDto();
                            pyqJobDetailDeleteDto.setId(pyqJobDetailVo.getId());
                            pyqJobDetailDeleteDto.setPyqId(pyqJobDetailVo.getPyqId());
                            //调用删除微信朋友方法
                            pyqJobDetailService.deleteWxPyq(pyqJobDetailDeleteDto);
                        }
                    }
                }
            }
        }

        try{
            //延迟0.1秒
            Thread.sleep(100);
        }catch (Exception e){
        }

    }

    /**
     * 开启发送任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqJobIdDto
     * @return null
     */
    public void startPyqJob(PyqJobIdDto pyqJobIdDto){
        if(pyqJobIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqJob pyqJob = pyqJobMapper.selectById(pyqJobIdDto.getId(), pyqJobIdDto.getMerId());

        if(pyqJob == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此朋友圈任务不存在");
        }

        if(pyqJob.getStatus().intValue() != PyqJobStatusEnum.NOSTART.getValue().intValue()){//状态不等于完成
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此朋友圈任务不是未开始状态");
        }

        Integer now = DateUtil.getNowTime();
        pyqJob.setSendTime(now);
        pyqJob.setUpdateTime(now);
        pyqJobMapper.updateById(pyqJob);
    }
}
